package models

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

//门诊结算
type SaCollectfeesDoctororder struct {
	Id                             int64                             `json:"id"`
	Archives                       *Archives                         `orm:"rel(fk);null;on_delete(do_nothing)" json:"archives"`
	DepartmentId                   int64                             `json:"department_id"`
	ParentId                       int64                             `json:"parent_id"`
	Number                         string                            `json:"number"`
	TotalMoney                     float64                           `json:"total_money"`        //总金额
	SumPayable                     float64                           `json:"sum_payable"`        //应付金额
	Status                         int                               `json:"status"`             //状态0正常1已退费
	AlipayMoney                    float64                           `json:"alipay_money"`       //支付宝
	WechatMoney                    float64                           `json:"wechat_money"`       //微信支付
	CardMoney                      float64                           `json:"card_money"`         //刷卡支付
	CashMoney                      float64                           `json:"cash_money"`         //现金
	DetailIds                      string                            `json:"detail_ids" orm:"-"` //医嘱ID
	CreatedAt                      int64                             `json:"created_at"`
	CreatedBy                      string                            `json:"created_by"`
	SaCollectfeesDoctororderMiddle []*SaCollectfeesDoctororderMiddle `orm:"-" json:"doctor_order"`
}

func (a *SaCollectfeesDoctororder) TableName() string {
	return SaCollectfeesDoctororderTableName()
}

func SaCollectfeesDoctororderTableName() string {
	return TableName("sa_collectfees_doctororder")
}

//查询
type SaCollectfeesDoctororderQueryParam struct {
	BaseQueryParam
	Filter       string `json:"filter"` //姓名查询
	StartDate    string `json:"start_date"`
	EndDate      string `json:"end_date"`
	DepartmentId int64  `json:"department_id"`
}

//查询列表数据
func SaCollectfeesDoctororderList(params *SaCollectfeesDoctororderQueryParam) []*SaCollectfeesDoctororder {

	query := orm.NewOrm().QueryTable(SaCollectfeesDoctororderTableName()).RelatedSel("Archives")
	data := make([]*SaCollectfeesDoctororder, 0)

	cond := orm.NewCondition();
	if len(params.Filter) > 0 {
		cond1 := orm.NewCondition()
		cond = cond.AndCond(cond1.Or("Archives__pinyin__contains", params.Filter).Or("Archives__realname__contains", params.Filter).Or("Archives__mobile__contains", params.Filter))
	}
	query = query.SetCond(cond)
	if len(params.StartDate) > 0 {
		query = query.Filter("created_at__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("created_at__lte", utils.GetDateParse(params.EndDate)+86400)
	}
	query = query.Filter("department_id", params.DepartmentId)

	query.OrderBy("-id").All(&data)

	return data
}

//查询分页列表数据
func SaCollectfeesDoctororderPageList(params *SaCollectfeesDoctororderQueryParam) ([]*SaCollectfeesDoctororder, int64) {

	query := orm.NewOrm().QueryTable(SaCollectfeesDoctororderTableName()).RelatedSel("Archives")
	data := make([]*SaCollectfeesDoctororder, 0)

	cond := orm.NewCondition();
	if len(params.Filter) > 0 {
		cond1 := orm.NewCondition()
		cond = cond.AndCond(cond1.Or("Archives__pinyin__contains", params.Filter).Or("Archives__realname__contains", params.Filter).Or("Archives__mobile__contains", params.Filter))
	}
	query = query.SetCond(cond)
	if len(params.StartDate) > 0 {
		query = query.Filter("created_at__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("created_at__lte", utils.GetDateParse(params.EndDate)+86400)
	}
	query = query.Filter("department_id", params.DepartmentId)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total

}

//按时间查询数量
func QuerySaCollectfeesDoctororderCount(depid int64, starttime, endtime int64) int64 {
	query := orm.NewOrm().QueryTable(SaCollectfeesDoctororderTableName())
	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("CreatedAt__gte", starttime).And("CreatedAt__lte", endtime))
	query = query.SetCond(cond)
	query = query.Filter("department_id", depid)
	count, _ := query.Count()
	return count
}

//单条修改查询
func GetSaCollectfeesDoctororderById(id int64) (*SaCollectfeesDoctororder, error) {
	r := new(SaCollectfeesDoctororder)
	orm.NewOrm().QueryTable(SaCollectfeesDoctororderTableName()).RelatedSel("Archives").Filter("id", id).One(r)
	if r.Id == 0 {
		return nil, errors.New("没有找到数据")
	}
	//获取明细数据
	detail := make([]*SaCollectfeesDoctororderMiddle, 0)
	dq := orm.NewOrm().QueryTable(SaCollectfeesDoctororderMiddleTableName()).RelatedSel("Doctororder", "Doctororder__Number")
	dq = dq.Filter("collectfees_id", id)
	dq.All(&detail)
	r.SaCollectfeesDoctororderMiddle = detail
	return r, nil
}

//获取医嘱结帐明细
func GetSaCollectfeesDoctororderDetails(params *SaCollectfeesDoctororderQueryParam) []*DoDoctorOrder {
	sql := "SELECT a.* FROM " + DoDoctorOrderTableName() + " as a  LEFT JOIN " + SaCollectfeesDoctororderTableName() + " as b ON a.id IN(b.detail_ids) WHERE "

	sql = fmt.Sprintf("%s b.department_id = %d", sql, params.DepartmentId)
	if len(params.StartDate) > 0 {
		sql = fmt.Sprintf("%s AND b.created_at>=%d", sql, utils.GetTimeParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		sql = fmt.Sprintf("%s AND b.created_at<=%d", sql, utils.GetTimeParse(params.EndDate))
	}
	o := orm.NewOrm()
	var dor []*DoDoctorOrder
	o.Raw(sql).QueryRows(&dor)
	return dor
}
